from flask import Flask,request
from storage_mysql import TodoStorageWithMySQL

a = TodoStorageWithMySQL()
app = Flask(__name__)
app.config['JSON_AS_ASCII']=False
@app.route('/')
def respon():
    return '<h1>hello world</h1>'
@app.route('/todo',methods = ['GET'])
def get_todo():
    if request.args['completed'] == '1':
        return {"todo": [x.__dict__ for x in a.list_todos() if x.completed]}
    elif request.args['completed'] == '0':
        return {"todo": [x.__dict__ for x in a.list_todos() if not x.completed]}
    elif request.args['completed'] =='all':
        return {"todo": [x.__dict__ for x in a.list_todos()]}
@app.route('/create_todo',methods=['POST'])
def created():
    if 'title' not in request.json:
        return '参数错误，必须提供title参数',400
    todo = a.create(request.json['title'])
    return todo.__dict__
@app.route('/mark_completed',methods=['GET'])
def change():

    """
    创建待办事项接口
        参数： title，表示待办事项的内容
        成功，返回已创建的待办事项 JSON 表示
    """
    if 'id' not in request.args:
        return '参数错误，必须提供 id 参数', 400
    id = int(request.args['id'])
    todo = a.mark_completed(id)
    return todo.__dict__
@app.route("/del_title", methods=['GET'])
def del_title():
    if 'title' not in request.args:
        return '参数错误，必须提供 id 参数', 400
    todo_title = request.args['title']
    todo = a.del_todos(todo_title)
    return todo.__dict__

if __name__ == '__main__':
    app.run()

